<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item label='选择文件'>
            <input type="file" @change="onchange"  accept=".xlsx,.xls" />
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
    import { importApi } from '@/api/StudentDatabase';
import { schoolLeveleApi } from '@/api/system/Dictionary';
        import { ref } from 'vue';
    import * as XLSX from 'xlsx';


    function readFileAsync(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve(e.target.result);
            reader.onerror = reject;
            reader.readAsArrayBuffer(file); // 可以换成 readAsBinaryString/readAsText 等
        });
    }



    const formRef = ref()

    let file:File = null

    
    const formData = ref<any>({
        id : 0,
        name : '',
        cover : '',
        link : '',
        sort : 1,
        enable : true

    })

    const schoolLevelMap = ref<{string?:any}>({

    })


    function onchange(e) {
        file = e.target.files[0]
        
    }


    

    async function submit() {
        if(!file) return

        const dataBuffer = await readFileAsync(file);
        
        const workbook = XLSX.read(new Uint8Array(dataBuffer), { type: 'array' });

        const sheetName = workbook.SheetNames[0];
        const sheet = workbook.Sheets[sheetName];
        let json = XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1 });
        const data:any[] = []
        let len = json.length
        for(let i = 1; i < len; i ++) {
            const item = json[i]
            if(item.length > 0) {
                data.push({
                    school: item[0],
                    name: item[1],
                    gender: item[2] == '男' ? 1 : 2,
                    level: schoolLevelMap.value[item[3]],
                    year: item[4],
                    className: item[5]
                })
            }
        }

        if(data.length > 0) {
            return importApi(data)
        }

    }


    schoolLeveleApi().then(rows => {
        rows.forEach(row => {
            schoolLevelMap.value[row.name] = Number(row.code)
        })

        console.log(schoolLevelMap.value)
    })
    


    defineExpose({
        submit
    })
</script>